﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using MangaEplision.MangaView;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Threading;

namespace MangaEplision
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                string dbfolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MangaEplision";
                string dbfile = dbfolder + "\\animecatalog.bin";
                if (System.IO.Directory.Exists(dbfolder) == false)
                {
                    System.IO.Directory.CreateDirectory(dbfolder);
                    
                }
                if (System.IO.File.Exists(dbfile) == false)
                {
                    if (MessageBox.Show("You do not have the latest anime catalog. Would you like to get started by downloading it?", "Catalog Download", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {

                        Collection<Manga> m = new Collection<Manga>();
                        Task t = Task.Factory.StartNew(delegate()
                        {
                            UpdateMangaCatalogWin umcw = null;
                            try
                            {
                                IFormatter formatter = new BinaryFormatter();
                                Stream stream = new FileStream(dbfile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);



                                MangaReaderSource mr = new MangaReaderSource();
                                Dispatcher.Invoke(new EmptyDelegate(delegate()
                                    {
                                        umcw = new UpdateMangaCatalogWin(mr.manganames.Count);
                                        umcw.Update("Downloading Manga..", 0);
                                        umcw.Show();
                                    }));
                                int tmes = 0;
                                for (int i = 0; i < mr.manganames.Count; i++)
                                {
                                    try
                                    {
                                        string n = mr.manganames[i];
                                        m.Add(mr.GetMangaInfo(n));


                                        tmes += 1;

                                        if (tmes == 30)
                                        {
                                            Thread.Sleep(10000); //Call this to prevent this from being detected as a DDoS attack.
                                            tmes = 0;
                                        }
                                        Dispatcher.Invoke(new EmptyDelegate(delegate()
                                        {
                                            umcw.Update("Manga Downloaded:", i + 1);
                                        }));
                                    }
                                    catch (Exception) { }
                                }
                                formatter.Serialize(stream, m);
                                stream.Close();
                            }
                            catch (Exception)
                            {

                            }
                            Dispatcher.Invoke(new EmptyDelegate(delegate()
                            {
                                umcw.Close();
                            }));
                        });

                    }

                }
                else
                {
                    IFormatter formatter = new BinaryFormatter();
                    Stream stream = new FileStream(dbfile, FileMode.Open, FileAccess.Read, FileShare.None);

                    Collection<Manga> m = (Collection<Manga>)formatter.Deserialize(stream);
                    stream.Close();
                    foreach (Manga man in m)
                    {
                        try
                        {
                            var mlb = new MangaListItem(man, ref tabControl1,false);

                            FindMangaListView.Items.Add(mlb);
                        }
                        catch (Exception)
                        { }
                    }
                }

                
            }
            catch (Exception) { }
            
        }
        private delegate void EmptyDelegate();
        private void ReloadBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void FindBtn_Click(object sender, RoutedEventArgs e)
        {
#if DEBUG
            MangaReaderSource mr = new MangaReaderSource(false);

            var mlb = new MangaListItem(mr.GetMangaInfo("Sora no Otoshimono")
                , ref tabControl1, false);

            FindMangaListView.Items.Add(mlb);
#endif
        }
    }
}
